package logic

import (
	"context"
	"fmt"
	"math/rand"
	"strconv"
	"time"
	"user/model/redis"
	"user/pkg"

	"user/userrpc/internal/svc"
	"user/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *userrpc.SendSmsRequest) (*userrpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line

	get := redis.Client.Get("sendSmsOne" + in.Source + in.Tel)
	if get.Val() >= "1" {
		return nil, fmt.Errorf("五分钟内只允许发送一条")
	}

	hour := redis.Client.Get("sendSmsHour" + in.Source + in.Tel)
	if hour.Val() >= "10" {
		return nil, fmt.Errorf("2小时内只允许发送十次")
	}

	code := rand.Intn(9000) + 1000

	sms, err := pkg.SendSms(in.Tel, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}
	if *sms.Body.Code != "OK" {
		return nil, fmt.Errorf(*sms.Body.Message)
	}
	redis.Client.Set("sendSms"+in.Source+in.Tel, code, time.Minute*3)

	incr := redis.Client.Incr("sendSmsOne" + in.Source + in.Tel)

	if incr.Val() == 1 {
		redis.Client.Expire("sendSmsOne"+in.Source+in.Tel, time.Minute*3)
	}

	cmd := redis.Client.Incr("sendSmsHour" + in.Source + in.Tel)

	if cmd.Val() == 1 {
		redis.Client.Expire("sendSmsHour"+in.Source+in.Tel, time.Hour*2)
	}

	return &userrpc.SendSmsResponse{}, nil
}
